<!DOCTYPE html>
<html>
<head>
    <title>PDF对比</title>
    <!-- 引入 PDF.js 库 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
    <style>
        .container {
            display: flex;
            flex-direction: column;
            gap: 20px;
            margin: 20px;
        }
        .image-row {
            display: flex;
            gap: 20px;
            justify-content: center;
        }
        .diff-row {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 2px dashed #ccc;
        }
        canvas {
            border: 1px solid #ccc;
            max-width: 800px;
            width: 100%;
            height: auto;
        }
        .debug-info {
            margin-top: 20px;
            padding: 10px;
            background: #f0f0f0;
            width: 100%;
            max-width: 1600px;
            margin: 20px auto;
        }
        .image-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            width: 45%;
        }
        .page-controls {
            margin: 10px 0;
        }
        h3 {
            margin-bottom: 10px;
            color: #333;
        }
        @media (max-width: 1200px) {
            canvas {
                max-width: 600px;
            }
            .image-container {
                width: 48%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="image-row">
            <div class="image-container">
                <h3>PDF文件 1</h3>
                <input type="file" id="pdf1" accept="application/pdf">
                <div class="page-controls">
                    <button onclick="changePage(1, -1)">上一页</button>
                    <span id="page1">第 1 页</span>
                    <button onclick="changePage(1, 1)">下一页</button>
                </div>
                <canvas id="canvas1"></canvas>
            </div>
            <div class="image-container">
                <h3>PDF文件 2</h3>
                <input type="file" id="pdf2" accept="application/pdf">
                <div class="page-controls">
                    <button onclick="changePage(2, -1)">上一页</button>
                    <span id="page2">第 1 页</span>
                    <button onclick="changePage(2, 1)">下一页</button>
                </div>
                <canvas id="canvas2"></canvas>
            </div>
        </div>
        <div class="diff-row">
            <h3>差异对比图</h3>
            <div class="diff-controls" style="margin-bottom: 10px;">
                <label>
                    差异阈值:
                    <input type="range" id="diffThreshold" min="15" max="100" value="30" style="width: 200px;">
                    <span id="thresholdValue">30</span>
                </label>
                <label style="margin-left: 20px;">
                    模糊度:
                    <input type="range" id="blurLevel" min="0" max="5" value="1" step="1" style="width: 100px;">
                    <span id="blurValue">1</span>
                </label>
            </div>
            <canvas id="diffCanvas"></canvas>
        </div>
        <div class="debug-info" id="debugInfo"></div>
    </div>

    <script>
        // 初始化 PDF.js
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

        const canvas1 = document.getElementById('canvas1');
        const canvas2 = document.getElementById('canvas2');
        const diffCanvas = document.getElementById('diffCanvas');
        const ctx1 = canvas1.getContext('2d');
        const ctx2 = canvas2.getContext('2d');
        const diffCtx = diffCanvas.getContext('2d');
        const debugInfo = document.getElementById('debugInfo');

        let pdf1 = null;
        let pdf2 = null;
        let currentPage1 = 1;
        let currentPage2 = 1;
        let diffThreshold = 30;
        let blurLevel = 1;

        function log(message) {
            console.log(message);
            debugInfo.innerHTML += message + '<br>';
        }

        async function loadPDF(file, canvasId, pdfNum) {
            try {
                const arrayBuffer = await file.arrayBuffer();
                const pdf = await pdfjsLib.getDocument(arrayBuffer).promise;
                
                if (pdfNum === 1) {
                    pdf1 = pdf;
                    currentPage1 = 1;
                } else {
                    pdf2 = pdf;
                    currentPage2 = 1;
                }

                log(`PDF ${pdfNum} 加载成功，共 ${pdf.numPages} 页`);
                await renderPage(pdfNum);
                
                if (pdf1 && pdf2) {
                    comparePages();
                }
            } catch (error) {
                log(`PDF ${pdfNum} 加载失败: ${error.message}`);
            }
        }

        async function renderPage(pdfNum) {
            const canvas = pdfNum === 1 ? canvas1 : canvas2;
            const ctx = pdfNum === 1 ? ctx1 : ctx2;
            const pdf = pdfNum === 1 ? pdf1 : pdf2;
            const pageNum = pdfNum === 1 ? currentPage1 : currentPage2;
            const pageSpan = document.getElementById(`page${pdfNum}`);

            try {
                const page = await pdf.getPage(pageNum);
                const viewport = page.getViewport({ scale: 1.5 });
                
                canvas.width = viewport.width;
                canvas.height = viewport.height;

                await page.render({
                    canvasContext: ctx,
                    viewport: viewport
                }).promise;

                pageSpan.textContent = `第 ${pageNum} 页 / 共 ${pdf.numPages} 页`;
                
                if (pdf1 && pdf2) {
                    comparePages();
                }
            } catch (error) {
                log(`页面渲染失败: ${error.message}`);
            }
        }

        async function changePage(pdfNum, delta) {
            if (pdfNum === 1 && pdf1) {
                currentPage1 = Math.max(1, Math.min(currentPage1 + delta, pdf1.numPages));
                await renderPage(1);
            } else if (pdfNum === 2 && pdf2) {
                currentPage2 = Math.max(1, Math.min(currentPage2 + delta, pdf2.numPages));
                await renderPage(2);
            }
        }

        function comparePages() {
            const width = Math.min(canvas1.width, canvas2.width);
            const height = Math.min(canvas1.height, canvas2.height);

            diffCanvas.width = width;
            diffCanvas.height = height;

            const imageData1 = ctx1.getImageData(0, 0, width, height);
            const imageData2 = ctx2.getImageData(0, 0, width, height);
            const diffImageData = diffCtx.createImageData(width, height);

            let diffCount = 0;

            function getAverageColor(imageData, x, y, size) {
                let r = 0, g = 0, b = 0, count = 0;
                const radius = Math.floor(size / 2);
                
                for (let dy = -radius; dy <= radius; dy++) {
                    for (let dx = -radius; dx <= radius; dx++) {
                        const nx = x + dx;
                        const ny = y + dy;
                        if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
                            const i = (ny * width + nx) * 4;
                            r += imageData.data[i];
                            g += imageData.data[i + 1];
                            b += imageData.data[i + 2];
                            count++;
                        }
                    }
                }
                return {
                    r: r / count,
                    g: g / count,
                    b: b / count
                };
            }

            for (let y = 0; y < height; y++) {
                for (let x = 0; x < width; x++) {
                    const i = (y * width + x) * 4;
                    
                    const color1 = getAverageColor(imageData1, x, y, blurLevel * 2 + 1);
                    const color2 = getAverageColor(imageData2, x, y, blurLevel * 2 + 1);

                    const diffR = Math.abs(color1.r - color2.r);
                    const diffG = Math.abs(color1.g - color2.g);
                    const diffB = Math.abs(color1.b - color2.b);

                    if (diffR > diffThreshold || diffG > diffThreshold || diffB > diffThreshold) {
                        diffCount++;
                        diffImageData.data[i] = 255;
                        diffImageData.data[i + 1] = 0;
                        diffImageData.data[i + 2] = 0;
                        diffImageData.data[i + 3] = 128;
                    } else {
                        diffImageData.data[i] = imageData1.data[i];
                        diffImageData.data[i + 1] = imageData1.data[i + 1];
                        diffImageData.data[i + 2] = imageData1.data[i + 2];
                        diffImageData.data[i + 3] = imageData1.data[i + 3];
                    }
                }
            }

            diffCtx.drawImage(canvas1, 0, 0);
            diffCtx.putImageData(diffImageData, 0, 0);

            const totalPixels = width * height;
            const diffPercentage = (diffCount / totalPixels) * 100;
            
            debugInfo.innerHTML = '';
            log(`当前对比：第 ${currentPage1} 页 vs 第 ${currentPage2} 页`);
            log(`页面尺寸: ${width} x ${height} 像素`);
            log(`发现差异: ${diffCount} 个像素`);
            log(`差异比例: ${diffPercentage.toFixed(2)}%`);
            if (diffCount > 0) {
                log('红色半透明区域表示差异部分');
            }
        }

        document.getElementById('pdf1').addEventListener('change', function(e) {
            if (e.target.files[0]) {
                debugInfo.innerHTML = '';
                loadPDF(e.target.files[0], 'canvas1', 1);
            }
        });

        document.getElementById('pdf2').addEventListener('change', function(e) {
            if (e.target.files[0]) {
                debugInfo.innerHTML = '';
                loadPDF(e.target.files[0], 'canvas2', 2);
            }
        });

        document.getElementById('diffThreshold').addEventListener('input', function(e) {
            diffThreshold = parseInt(e.target.value);
            document.getElementById('thresholdValue').textContent = diffThreshold;
            if (pdf1 && pdf2) comparePages();
        });

        document.getElementById('blurLevel').addEventListener('input', function(e) {
            blurLevel = parseInt(e.target.value);
            document.getElementById('blurValue').textContent = blurLevel;
            if (pdf1 && pdf2) comparePages();
        });
    </script>
</body>
</html> 